package cn.jdy.plugins.web;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.platform.entity.News;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.service.NewspService;
/**
 * 在线投稿
 * 投稿使用news表，投稿成功状态为0，审核通过状态为1
 * @author yym
 * @since Apr 2016
 */

@Controller
@RequestMapping("/article")
public class ArticleEditCtrl extends BaseCtrl {
	
	@Autowired
	private NewspService newsService;
	@Autowired
	private ConfService confService;
	
	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/index.html")
	public ModelAndView edit() {
		return edit(null);
	}
	
	/**
	 * 特警
	 * 新增
	 * @return
	 */
	@RequestMapping("/art")
	public ModelAndView edits() {
		return edits(null);
	}

	/**
	 * 特警
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edits/{id}")
	public ModelAndView edits(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/article/article.jsp");
		mv.addObject("column", this.confService.queryByType(GlobalConstant.TYPE_NEWS, 0L));
		mv.addObject("data", id==null||id==0 ? id : this.newsService.find(id));
		return mv;
	}

	/**
	 * 市局
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/article/article.jsp");
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		
		mv.addObject("column", this.confService.queryByType(GlobalConstant.TYPE_NEWS, 0L));
		mv.addObject("data", id==null||id==0 ? id : this.newsService.find(id));
		mv.addObject("column1", confService.findConfValueByPid(10242L));
		mv.addObject("ctime", DateUtil.getCurrentDate(DateUtil._DEFAULT2));
		return mv;
	}

	/**
	 * 特警
	 * 保存（更新）文章
	 * @param news
	 * @return
	 */
	@RequestMapping("/saves")
	public ModelAndView saves(News news,Long pid) {
		ModelAndView mv = new ModelAndView("/article/articleOk.jsp");
		try {
			//如果二级新闻类别为空，则使用一级类别
		      if(null == news.getColumnId()) {
		        news.setColumnId(pid);
		      }
			if(news.getId()==null) {// 新增文章
				news.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				this.newsService.save(news);
			} else {//更新文章
				this.newsService.update(news);
		    // 清理文章缓存
		    NginxPurgeCacheUtil.purge(2, news.getId());
			}
			// 清理栏目列表缓存
			NginxPurgeCacheUtil.purge(1, news.getColumnId());
		} catch(Exception e) {
			BaseLog.e(getClass(), "投稿保存异常！", e);
		}
		return mv;
	}
	
	/**
	 * 市局
	 * 投稿 保存文章，基本上无（更新）
	 * @param news
	 * @return
	 */
	@RequestMapping("/save")
	public ModelAndView save(News news,Long pid) {
		ModelAndView mv = new ModelAndView("/article/articleOk.jsp");
		//将数组转化成String
		String[] ds=news.getDepartments();
		String deps = "";
		for(int i=0;i<46;i++){
			if(ds[i]==null || ds[i]=="")ds[i]=";";
			deps += ","+ds[i];
		}
		news.setDepars(deps);
		news.setDepartments(null);
		news.setIsarticle("1");       //add with daihu 表示是从前台投稿管理的文章
		//襄阳市公安局，需要加入当前时间段周数
		//
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		try {
			//如果二级新闻类别为空，则使用一级类别
		      if(null == news.getColumnId()) {
		        news.setColumnId(pid);
		      }
			if(news.getId()==null) {// 新增文章
				news.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				if(news.getFalseCreateTime() == null || news.getFalseCreateTime() == ""){
					news.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				this.newsService.save(news);
			} else {//更新文章
				if(news.getFalseCreateTime() == null || news.getFalseCreateTime() == ""){
					news.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				this.newsService.update(news);
		    // 清理文章缓存
		    NginxPurgeCacheUtil.purge(2, news.getId());
			}
			// 清理栏目列表缓存
			NginxPurgeCacheUtil.purge(1, news.getColumnId());
		} catch(Exception e) {
			BaseLog.e(getClass(), "投稿保存异常！", e);
		}
		return mv;
	}
	
	/**
	 * 市局
	 * 投稿文章状态为未审核
	 * @param news
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView queryByPage(News news, String fromDate, String toDate) {
		ModelAndView mv = new ModelAndView("/article/chooseArticleList.jsp");
		try {
			//襄阳市公安局，需要加入当前时间段周数
			Date datetime = new Date();
			int weekdays = datetime.getDay();
			mv.addObject("weekdays",weekdays);
						
			news.setStatus("0");//未审核
			mv.addObject("dataList",newsService.query1(news, fromDate, toDate));
			// 设置分页信息
			if (news.getiDisplayLength() == 0)
				news.setiDisplayLength(24); // 默认长度24
			if (news.getPageNo() <= 0)
				news.setPageNo(1); // 默认页数1
			news.setiDisplayStart((news.getPageNo() - 1)
					* news.getiDisplayLength()); // 显示起始索引
			mv.addObject("pageNo", 1);//
			
			mv.addObject("total",newsService.count1(news, fromDate, toDate));
			mv.addObject("iTotalRecords",newsService.count());
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return mv;
	}
	
	/**
	 * 市局
	 * 前端审核
	 * @param id
	 * @return
	 */
	@RequestMapping("/show-{id}.html")
	public ModelAndView edita(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/article/chooseArticles.jsp");
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		
		mv.addObject("column", this.confService.queryByType(GlobalConstant.TYPE_NEWS, 0L));
//		mv.addObject("data", id==null||id==0 ? id : this.newsService.find(id));
		if(id==null || id==0){
			mv.addObject("data", id);
		}else{
			News news = this.newsService.find(id);
			//投稿统计，将department置null,现将其复原到页面回显
			String[] nd = news.getDepartments();
			if(nd == null){
				String temp=news.getDepars();
				String[] st=temp.split(",");
				int cnt=st.length;
				String[] nds = new String[cnt-1];
				for(int i=1;i<cnt;i++){
					nds[i-1]=st[i];
				}
				news.setDepartments(nds);;
			}
			mv.addObject("data", news);
		}
		return mv;
	}

	/**
	 * 市局
	 * 前端审核后，保存（审核）投稿
	 * @param news
	 * @return
	 */
	@RequestMapping("/adminSave")
	public ModelAndView savea(News news, Long pid) {
		ModelAndView mv = new ModelAndView("/article/article1Ok.jsp");
		try {
			//如果二级新闻类别为空，则使用一级类别
      if(null == news.getColumnId()) {
        news.setColumnId(pid);
      }
	      String[] nd = news.getDepartments();
	      String names = "";
	      for(int i=0;i<nd.length;i++){
	    	  if(nd[i]!=null)
	    		  names+=nd[i]+" ";
	      }
	      if(names.equals("")){
	    	  User user = getUser();
	    	  news.setUserid(user.getId());
	    	  names = user.getUsername();
	      }
	      news.setUsername(names);
			if(news.getFalseCreateTime() == null || news.getFalseCreateTime() == ""){
				news.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
			}//市局
		//更新文章
//			news.setCreateTime(news.getCreateTime());//市局？
			this.newsService.update(news);
	    // 清理文章缓存
	    NginxPurgeCacheUtil.purge(2, news.getId());
		// 清理栏目列表缓存
		NginxPurgeCacheUtil.purge(1, news.getColumnId());
		} catch(Exception e) {
			BaseLog.e(getClass(), "审核保存异常！", e);
		}

		return mv;
	}
	
	/**
	 * 市局
	 * 删除新闻
	 * @return
	 */
	@RequestMapping("/adminDel/{id}")
	public ModelAndView dela(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		try {
			this.newsService.delete(id);
			// 清理文章缓存
            NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			BaseLog.e(getClass(), "删除异常！", e);
		}
		return mv;
	}
	/**
	 * 投稿详细
	 * @param name
	 * @return
	 */
	@RequestMapping("/{name}.html")
	public ModelAndView articleDels(News entity, @PathVariable String name) {
		ModelAndView mv = new ModelAndView("/article/articleDelslist.jsp");
		try {
			entity.setUsername(name);
			  //设置分页信息
		      if(entity.getiDisplayLength() == 0) entity.setiDisplayLength(10);                //默认长度5
		      if(entity.getPageNo()<=0) entity.setPageNo(1);                                  //默认页数1
		      entity.setiDisplayStart((entity.getPageNo() - 1) * entity.getiDisplayLength());  //显示起始索引
		   
		      mv.addObject("dataList", newsService.query(entity));
		      mv.addObject("iTotalDisplayRecords", newsService.count(entity));
		      mv.addObject("pageNo", entity.getPageNo());
		      mv.addObject("size", entity.getiDisplayLength());
		      mv.addObject("total", newsService.count(entity));
		      mv.addObject("entity", entity);    
		      mv.addObject("key", entity.getKeyword());    
	
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return mv;
	}

}
